<template>
  <div class="container">
    <el-dialog
      :title="form.id ? '编辑文章' : '新增文章'"
      :visible="isShow"
      @close="closeDialog"
      width="800px"
    >
      <el-form
        :model="form"
        ref="form"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="文章标题" style="width: 92%" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item label="文章内容 " style="width: 92%" prop="articleBody">
          <Tinymce v-model="form.articleBody" :height="400" ref="mce" />
        </el-form-item>

        <el-form-item label="视频地址 " style="width: 92%">
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="dialogOk">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
// 添加 文章详情
import { add, detail, update } from '@/api/hmmm/articles.js'
export default {
  components: {
    Tinymce
  },
  data () {
    return {
      a: null,
      form: {
        title: '', // 文章标题
        articleBody: '', // 文章内容
        videoURL: '' // 视频地址
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    isShow: {
      type: Boolean,
      default: false
    }
  },
  created () {
  },
  methods: {
    async getDetail (data) {
      // console.log(data)
      const { data: res } = await detail(data)
      // console.log(res)
      this.form = res
      this.$refs.mce.setContent(this.form.articleBody)
    },
    // 弹框
    // 关闭弹框
    closeDialog () {
      this.form = {
        title: '', // 文章标题
        articleBody: '', // 文章内容
        videoURL: '' // 视频地址
      }
      this.$refs.mce.setContent(this.form.articleBody)
      // 先让新的值传入到富文本插件 - 然后DOM更新后再关闭弹窗
      this.$nextTick(() => {
        this.$emit('update:isShow', false)
      })
    },
    // 弹框确认
    dialogOk () {
      // 兜底验证
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          if (this.form.id) {
            // 编辑
            await update({ id: this.form.id, title: this.form.title, articleBody: this.form.articleBody, videoURL: this.form.videoURL })
            // tip
            this.$message.success('编辑文章成功')
          } else {
            // 新增
            await add(this.form)
            // tip
            this.$message.success('新增文章成功')
          }

          // 关闭弹框
          this.closeDialog()

          // 刷新页面
          this.$parent.getData()
        }
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.dialog-footer {
  float: right;
  margin-top: -30px;
}
</style>
